package com.test.configcenter;

import com.alibaba.fastjson.JSON;
import lombok.SneakyThrows;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;

import java.sql.*;

public class ConfigCenter {
    private static ZkClient zkClient = null;
    private static Integer countNums = 0;
    private static Connection conn = null;

    public static void main(String[] args) {
        try {
            initClient();
            startJob();
            // 监听
            bindEvent();
        } catch (Exception e) {
            System.out.println(e);
        }
    }

    public static void initClient() {
        // 1. 建立会话
        zkClient = new ZkClient(Constants.ZK_CLIENT);
        System.out.println("zkclient is ready, ZooKeeper session established.");
    }

    public static void startJob() {
        // 2. 开始设置
        Runnable runnable = new Runnable() {
            @SneakyThrows
            public void run() {
                while (true) {
                    if (countNums == Constants.DB_CONNECT_STRS.length) {
                        countNums = 0;
                    }
                    setMysqlConfig(Constants.DB_CONNECT_STRS[countNums]);
                    System.out.println("zkclient config !!");
                    countNums++;
                    try {
                        Thread.sleep(Constants.TIME_INTERVAL);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        Thread thread = new Thread(runnable);
        thread.start();
    }

    /**
     * 更新MySQL配置
     */
    public static void setMysqlConfig(MysqlConfig config) {
        // 创建节点, createParents的值设置为true，可以递归创建节点
        final boolean exists = zkClient.exists(Constants.CONFIG_PATH);
        String mysqlConfigStr = JSON.toJSONString(config);
        if (!exists) {
            zkClient.createPersistent(Constants.CONFIG_PATH, true);
        }
        zkClient.writeData(Constants.CONFIG_PATH, mysqlConfigStr);
    }

    /**
     * 监听变化
     */
    public static void bindEvent() throws ClassNotFoundException, SQLException{
        // 监听变化
        zkClient.subscribeDataChanges(Constants.CONFIG_PATH, new IZkDataListener() {
            public void handleDataChange(String s, Object o) throws Exception {
                if (conn != null ) {
                    conn.close();
                }
                //定义接收通知之后的处理逻辑
                System.out.println(s + " data is changed ,new data " +
                        o);
                MysqlConfig config = JSON.parseObject(o.toString(), MysqlConfig.class);
                Class.forName(config.getDriver());
                conn = DriverManager.getConnection(config.getUrl(), config.getUsername(), config.getPassword());
                queryMysql();
            }

            public void handleDataDeleted(String s) throws Exception {
                System.out.println(s + " is deleted!!");
            }
        });
    }

    /**
     * 通过配置信息，查询MySQL数据库
     */
    public static synchronized void queryMysql() throws ClassNotFoundException, SQLException {
        if (conn == null) {
            return;
        }
        Statement statement = conn.createStatement();
        ResultSet resultSet = statement.executeQuery("select * from table1");
        while (resultSet.next()) {
            String str = String.format("id=%s, title=%s, content=%s", resultSet.getString(1), resultSet.getString(2), resultSet.getString(3));
            System.out.println(str);
        }
        resultSet.close();
        statement.close();
    }
}
